package model

import (
	"im-v1/database"
	"im-v1/tool"
)

type Usr struct {
	Id       int    `json:"id" gorm:"column:id;primary_key"`                                                    // 自增主键
	Mailbox  string `json:"mailbox" gorm:"column:mailbox" form:"mailbox" json:"mailbox" binding:"required"`     // 邮箱-唯一
	Password string `json:"password" gorm:"column:password" form:"password" json:"password" binding:"required"` // 密码
	Nickname string `json:"nickname" gorm:"column:nickname" form:"nickname" json:"nickname" binding:"required"` // 昵称
	HeadUrl  string `json:"head_url" gorm:"column:head_url"`                                                    // 头像url
	Status   int    `json:"status" gorm:"column:status"`                                                        // 个人状态
}

func (e *Usr) TableName() string {
	return "usr"
}

// 将 Usr 转换位 UsrOds
func (e *Usr) TransformOds() *UsrOds {
	var u UsrOds
	u.Nickname = e.Nickname
	u.Mailbox = e.Mailbox
	u.HeadUrl = e.Password
	u.Status = e.Status
	return &u
}

// 根据 mailbox 查找
func FindByMailbox(mailbox string) (int64, *Usr) {
	var usr Usr
	raw := database.Db.Where("mailbox = ?", mailbox).Find(&usr)
	return raw.RowsAffected, &usr
}

// insert Usr -> 密码需要加密
func NewUsr(usr *Usr) {
	usr.Password = tool.EncryptMD5(usr.Password)
	database.Db.Create(usr)
}

// update Usr -> 更新head_url
func UpdateUsrWithHeadUrl(mailbox, headUrl string) {
	database.Db.Model(&Usr{}).Where("mailbox = ?", mailbox).Update("head_url", headUrl)
}
